<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="loadForm" class="demo-form-inline">
      <el-form-item label="文件名称">
        <el-input
          v-model="loadForm.fileName"
          size="small"
          clearable
          placeholder="文件名称"
          @clear="listPageData"
          @keyup.enter.native="listPageData"
        />
      </el-form-item>

      <el-form-item label="分类">
        <el-select v-model="loadForm.mediaTypeId" filterable clearable placeholder="请选择分类" @clear="listPageData">
          <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="标签">
        <el-select v-model="loadForm.mediaTagId" filterable clearable placeholder="请选择标签" @clear="listPageData">
          <el-option v-for="item in tagList" :key="item.id" :label="item.tagName" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-search" type="primary" size="mini" @click="listData">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      highlight-current-row
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />

      <el-table-column label="文件名称" prop="fileName" align="center" />
      <el-table-column label="分类" prop="mediaTypeName" align="center" />
      <el-table-column label="标签" prop="tagNames" align="center" />

      <el-table-column label="文件封面" prop="fileCover" align="center">
        <template slot-scope="scope">
          <el-image :src="scope.row.fileCover" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="loadForm.pageNum"
      :limit.sync="loadForm.pageSize"
      @pagination="listPageData"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">

        <el-form-item v-if="showUpdate()" label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" clearable placeholder="请输入文件名称" />
        </el-form-item>

        <el-form-item v-if="showUpdate()" label="分类">
          <el-select v-model="form.mediaTypeId" filterable clearable placeholder="请选择分类" style="width: 380px;">
            <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="showUpdate()" label="标签">
          <el-select
            v-model="form.mediaTagIdList"
            filterable
            clearable
            multiple
            placeholder="请选择标签"
            style="width: 380px;"
          >
            <el-option v-for="item in tagList" :key="item.id" :label="item.tagName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="!showUpdate()" label="视频文件" prop="file">
          <el-upload
            class="avatar-uploader"
            action="#"
            drag
            :http-request="requestUploadVideo"
            :show-file-list="false"
            :on-remove="handleRemove"
            :before-upload="beforeUploadVideo"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item v-if="showUpdate()" label="视频封面" prop="fileCover" label-width="100px">
          <el-image style="width: 100%; height: auto;" :src="form.fileCover" fit="contain" />
        </el-form-item>

        <el-form-item v-if="showUpdate()" label="替换封面" label-width="100px">
          <el-upload
            class="avatar-uploader"
            action="#"
            drag
            :http-request="requestUpload"
            :show-file-list="false"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button v-if="showUpdate()" size="mini" type="primary" @click="replaceCover">替 换</el-button> -->
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>

import Pagination from '@/components/Pagination'
import { load, uploadCover, uploadVideo, update, downExcel, remove, getDetail } from '@/api/video/video.js'
import { listTypeInfo } from '@/api/video/type'
import { listTagInfo } from '@/api/video/tag'

export default {
  name: 'AdMedia',
  // 加载分页组件
  components: { Pagination },
  data() {
    return {
      // 表格数据
      tableData: [],
      // 默认当前页
      currentPage: 1,
      // 总页数
      totalCount: 0,
      // 导出遮罩层
      exportLoading: false,
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 弹出层标题
      title: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // id集合
      ids: [],
      // 查询条件
      loadForm: {
        pageNum: 1,
        pageSize: 10,
        // 具体查询条件
        fileName: undefined,
        mediaTagId: undefined,
        mediaTypeId: undefined
      },
      // 通用详情/删除条件
      commonForm: {
        id: undefined,
        idList: [],
        tableName: 'ad_media'
      },
      filleData: undefined,
      imageUrl: undefined,
      videoFile: undefined,
      // 分类搜素条件
      typeLoadData: {
        typeName: undefined,
        loadCount: 1000
      },
      // 标签搜素条件
      tagLoadData: {
        tagName: undefined,
        loadCount: 1000
      },
      typeList: undefined,
      tagList: undefined
    }
  },

  // 钩子函数
  created() {
    this.listPageData()
    this.handListTypeInfo()
    this.handListTagInfo()
  },
  methods: {
    requestUploadVideo() {
      console.log('处理上传视频')
      this.handUploadVideo()
    },

    handUploadVideo() {
      const data = this.videoFile
      const formData = new FormData()
      formData.append('file', data)
      uploadVideo(formData).then(res => {
        console.log(res.data.fileName, '完成上传')
        // 关闭弹窗
        this.open = false
        // 查询新数据
        this.listPageData()
      })
    },

    // 覆盖默认的上传行为
    requestUpload() {
      console.log('处理上传')
      this.replaceCover()
    },

    handleRemove(file, fileList) {
      // console.log(file, fileList)
    },

    beforeUploadVideo(file) {
      this.videoFile = file
    },

    beforeUpload(file) {
      console.log('上传前校验')
      // 上传前的校验，例如文件类型和大小
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      if (!isJPG && !isPNG) {
        this.$message.error('只能上传JPG/PNG文件!')
      }
      this.filleData = file
      return isJPG || isPNG
    },

    // 查询分类数据
    handListTypeInfo() {
      listTypeInfo(this.typeLoadData).then(res => {
        // console.log('分类信息', res.data)
        this.typeList = res.data
      })
    },

    // 查询标签数据
    handListTagInfo() {
      listTagInfo(this.tagLoadData).then(res => {
        // console.log('标签信息', res.data)
        this.tagList = res.data
      })
    },

    // 查询页面数据
    listPageData() {
      console.log('加载数据')
      load(this.loadForm).then(response => {
        this.tableData = response.data.records
        this.totalCount = response.data.total
      })
    },

    // 查询按钮操作
    listData() {
      this.listPageData()
    },

    // 重置按钮操作
    resetQuery() {
      this.resetForm()
      this.listData()
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 新增修改表单重置
    reset() {
      this.form = {}
      this.imageUrl = undefined
    },

    // 重置查询表单
    resetForm() {
      this.loadForm = {}
    },

    // 表格多选操作
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      // 单选状态 值为true 可操作表单上方修改按钮
      this.single = selection.length !== 1
      // 选中数据后可放开删除按钮
      this.multiple = !selection.length
    },

    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加'
    },

    // 删除按钮操作
    handleDelete(row) {
      const id = row.id || this.ids
      console.log('id 集合', id)

      // 处理ID集合
      if (row.id) {
        this.commonForm.idList = [id]
      } else {
        this.commonForm.idList = id
      }

      this.$modal.confirm('是否确认删除？')
        .then(() => {
          console.log('删除')
          remove(this.commonForm).then(res => {
            this.$modal.msgSuccess('操作成功')
            this.listData()
          })
        })
    },

    // 修改按钮操作
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      this.commonForm.id = id
      // 获取详情
      getDetail(this.commonForm).then(res => {
        this.form = res.data
        this.open = true
        this.title = '修改'
      })
    },

    // 是否为修改标签
    showUpdate() {
      return this.title === '修改'
    },

    // 替换图片
    replaceCover() {
      const data = this.filleData
      const formData = new FormData()
      formData.append('file', data)
      uploadCover(formData).then(res => {
        this.imageUrl = res.data
      })
    },

    // 提交按钮
    submitForm: function() {
      if (this.form.fileName === undefined && this.form.id === undefined) {
        console.log('上传文件,不做修改操作')
        this.open = false
        this.reset()
      } else {
        if (this.form.id === undefined) {
          console.log('新增')
          this.form.fileCover = this.imageUrl
          update(this.form).then((response) => {
            this.$modal.msgSuccess('操作成功')
            console.log('后续处理')
            this.open = false
            this.listData()
            this.reset()
          })
        } else {
          console.log('修改')
          this.form.fileCover = this.imageUrl
          update(this.form).then((response) => {
            this.$modal.msgSuccess('操作成功')
            console.log('后续处理')
            this.open = false
            this.listData()
            this.reset()
          })
        }
      }
    },

    // 导出excel
    handleExport() {
      this.loadForm.idList = this.ids
      console.log('导出操作 ids', this.loadForm.idList)
      this.$modal.confirm('是否确认导出数据项？')
        .then(() => {
          // console.log('导出操作函数')
          this.exportLoading = true
          downExcel(this.loadForm)
            .then(response => {
              // 获取响应头中的文件名
              const fileName = decodeURIComponent(response.headers['content-disposition'].split('=')[1])
              // 创建URL对象并指定blob数据
              const url = window.URL.createObjectURL(new Blob([response.data]))
              // 创建a标签并设置下载属性
              const link = document.createElement('a')
              link.href = url
              // 设置下载文件名
              link.setAttribute('download', fileName)
              // 添加到页面中并触发点击事件进行下载
              document.body.appendChild(link)
              link.click()
              // 下载完成后移除a标签并释放URL对象
              document.body.removeChild(link)
              window.URL.revokeObjectURL(url)
              this.exportLoading = false
              this.listPageData()
            })
            .catch(error => {
              console.error('下载Excel失败: ', error)
            })
        })
    }

  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
